package club.pinea.handler.lobby;

import club.pinea.annotations.Head;
import club.pinea.interfaces.TCPMessage;
import club.pinea.model.Seat;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.LobbyProto;
import club.pinea.send.MessageSend;
import club.pinea.service.SeatService;
import club.pinea.session.IOSession;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 座位更新handler
 * @author: 华上进
 * @createTime: 2021/6/29 17:02
 */
@Head(CommandProto.Command.C_S_UPDATE_ROOM_INFO_VALUE)
@Component
public class UpdateRoomInfoHandler implements TCPMessage<BasicProto.BaseMessage> {

    /**
     * redis座位操作服务类
     */
    @Autowired
    private SeatService seatService;


    @Override
    public void doMessage(BasicProto.BaseMessage msg, IOSession session) throws Exception {
        LobbyProto.UpdateRoomInfoRequest request = LobbyProto.UpdateRoomInfoRequest.parseFrom(msg.getBody());

        int roomId = request.getRoom();
        List<Seat> seatList = seatService.getRoomSeatDownSeatsByKey(roomId);
//        obj = new JSONObject();
//        obj.put("order", "success");
//        Map<String, Object> m = new HashMap<>();
//        m.put("seats", seatList);
//        m.put("userNum", seatList.size());
//        m.put("multiplyPower", selectMutiplyPower(roomId));
//        obj.put("room", m);//重新获取座位信息返回客户端
//        writeAndFlush(ctx, obj.toString());
        List<LobbyProto.Seat> seats = new ArrayList<>();
        seatList.forEach(s -> {
            LobbyProto.Seat.Builder seatFor = LobbyProto.Seat.newBuilder()
                    .setSeatId(s.getSeatId())
                    .setSeatStatus(s.getSeatStatus())
                    .setDate(s.getDate());
            if (s.getSeatUser() != null) {
                seatFor.setSeatUser(s.getSeatUser());
            }
            seats.add(seatFor.build());
        });
        LobbyProto.UpdateRoomInfoResponse response = LobbyProto.UpdateRoomInfoResponse.newBuilder()
                .setMultiplyPower(selectMutiplyPower(roomId))
                .addAllSeats(seats)
                .setRes(MessageSend.successRes())
                .build();
        // 返回消息
        MessageSend.sendToUser(response, session);
    }

    /**
     * 根据房间号判断房间倍率
     *
     * @param room
     * @return
     */
    private int selectMutiplyPower(int room) {
        switch (room) {//根据房间号判断房间倍率
            case 1:
                return 20;
            case 2:
                return 5;
            case 3:
                return 2;
        }
        return 0;
    }
}
